﻿using Google.Protobuf.WellKnownTypes;
using Mysqlx.Crud;
using S7Simulate.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using sz.db.model;

namespace S7Simulate
{
    public partial class ClearData : Form
    {
        public ClearData()
        {
            InitializeComponent();
        }

        private void btnLogClear_Click(object sender, EventArgs e)
        {
            //异步清除日志
            Task.Run(() =>
            {
                try
                {
                    Log4NetHelper.Debug($"开始操作清除日志");
                    //根据日期清除日志文件夹下的日志文件 只清除包含.log的文件
                    string logPath = lblLogPath.Text;
                    //获取设置的天数
                    var days = int.Parse(tbxLogDays.Text);
                    if (!string.IsNullOrEmpty(logPath))
                    {
                        DirectoryInfo dir = new DirectoryInfo(logPath);
                        int num = 0;
                        if (dir.Exists)
                        {
                            FileInfo[] files = dir.GetFiles();
                            Log4NetHelper.Debug($"获取总文件数成功:{files.Length}");
                            foreach (FileInfo file in files)
                            {
                                //如果日志在设置天数之前就删除
                                if (file.LastWriteTime < DateTime.Now.AddDays(-days) && file.FullName.Contains(".txt"))
                                {
                                    file.Delete();
                                    num++;
                                }
                            }
                            Log4NetHelper.Debug($"清除日志成功计数:{num}");
                            MessageBox.Show($"清除成功计数:{num}");
                        }
                    }
                    else
                    {
                        //请选择正确的文件夹
                        MessageBox.Show("请选择正确的文件夹");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            });

        }

        private void btnSelLogPath_Click(object sender, EventArgs e)
        {
            //选择文件夹
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                lblLogPath.Text = folderBrowserDialog.SelectedPath;
            }

        }

        private void btnClearDBData_Click(object sender, EventArgs e)
        {
            btnClearDBData.Enabled = false;
            var isbat = cbxIsbat.Checked;
            //异步根据设置日期清除数据库数据
            Task.Run(() =>
            {
                try
                {
                    //根据日期清除数据库数据
                    var days = int.Parse(txtDBDays.Text);
                    var dt = DateTime.Now.AddDays(-days);
                    var dtStr = dt.ToString("yyyy-MM-dd");
                    //先根据日期获取batch_task表中的数据 批次号存入集合 
                    List<string> listBatch = new List<string>();
                    SqlSugarClient sqlSugarClient = SqlSugarUtil.GetLocalMySqlClient();
                    SqlSugarClient midsqlSugarClient = SqlSugarUtil.GetMidMysqlClient();
                    List<batch_task> data = new List<batch_task>();
                    if (isbat)
                    {
                        data = sqlSugarClient.Queryable<batch_task>().Where(x => x.ProductDate < dt).ToList();
                    }
                    if (data.Count > 0)
                    {
                        foreach (var item in data)
                        {
                            listBatch.Add(item.BatchName);
                        }
                        Log4NetHelper.Debug($"获取到的批次数量为:{listBatch.Count}");
                    }
                    else
                    {
                        Log4NetHelper.Debug($"获取到的批次数量为:{listBatch.Count}");
                    }
                    if (listBatch.Count > 0 || !isbat)
                    {

                        var cutoffDate = DateTime.Now.AddDays(-days);
                        bool hasMoreToDelete = true;
                        //开始时间
                        var startTime = DateTime.Now;
                        Log4NetHelper.Debug($"开始时间:{startTime}");
                        //计数
                        int count = 0;
                        //清除bus_wood_information
                        try
                        {
                            while (hasMoreToDelete)
                            {

                                var idsToDelete = sqlSugarClient.Queryable<bus_wood_information>()
                                                     .Where(t => t.created_time < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }

                                count = count + sqlSugarClient.Deleteable<bus_wood_information>(idsToDelete).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除bus_wood_information成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除bus_wood_information,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除bus_wood_information成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除bus_wood_task
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<bus_wood_task>()
                                                     .Where(t => t.created_time < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }

                                count = count + sqlSugarClient.Deleteable<bus_wood_task>(idsToDelete).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除bus_wood_task成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除bus_wood_task,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除bus_wood_task成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除bus_package_list 索引 batchid影响速度 
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<bus_package_list>()
                                                     .Where(t => t.created_time < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }

                                count = count + sqlSugarClient.Deleteable<bus_package_list>(idsToDelete).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除bus_package_list成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除bus_package_list,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除bus_package_list成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除bus_packing_information
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<bus_packing_information>()
                                                     .Where(t => t.created_time < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }

                                count = count + sqlSugarClient.Deleteable<bus_packing_information>(idsToDelete).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除bus_packing_information成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除bus_packing_information,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除bus_packing_information成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除his_fault
                        try
                        {
                            //TrunCateTable
                            sqlSugarClient.DbMaintenance.TruncateTable<his_fault>();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除his_fault,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除his_fault成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除hot_fault
                        try
                        {
                            sqlSugarClient.DbMaintenance.TruncateTable<hot_fault>();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除hot_fault,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Info($"清除hot_fault成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除library_information_del
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<library_information_del>()
                                                     .Where(t => t.createdate < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }
                                count = count + sqlSugarClient.Deleteable<library_information_del>().WhereColumns(idsToDelete, it => new { it.id }).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除library_information_del成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除library_information_del,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除library_information_del成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除library_information_save
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<library_information_save>()
                                                     .Where(t => t.createdate < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }
                                count = count + sqlSugarClient.Deleteable<library_information_save>().WhereColumns(idsToDelete, it => new { it.id }).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除library_information_save成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除library_information_save,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除library_information_save成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除package_count_statistics
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<package_count_statistics>()
                                                     .Where(t => t.dates < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }

                                count = count + sqlSugarClient.Deleteable<package_count_statistics>(idsToDelete).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除package_count_statistics成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除package_count_statistics,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除package_count_statistics成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        hasMoreToDelete = true;
                        startTime = DateTime.Now;
                        count = 0;
                        //清除scanned_record
                        try
                        {
                            while (hasMoreToDelete)
                            {
                                var idsToDelete = sqlSugarClient.Queryable<scanned_record>()
                                                     .Where(t => t.create_date < cutoffDate)
                                                     .Take(1000)
                                                     .ToList();

                                if (!idsToDelete.Any())
                                {
                                    hasMoreToDelete = false;
                                    break;
                                }

                                count = count + sqlSugarClient.Deleteable<scanned_record>(idsToDelete).ExecuteCommand();
                                var endTime = DateTime.Now;
                                var total = endTime - startTime;
                                Log4NetHelper.Info($"清除scanned_record成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"清除scanned_record,{ex}");
                        }
                        finally
                        {
                            var endTime = DateTime.Now;
                            var total = endTime - startTime;
                            Log4NetHelper.Debug($"清除scanned_record成功，清除数量为:{count},清除耗时:{total.TotalSeconds}s");
                        }

                        var endZTime = DateTime.Now;
                        var totalZ = endZTime - startTime;
                        //Log4NetHelper.Debug($"整体清除结束时间:{endZTime}，耗时:{totalZ.TotalSeconds}s");


                    }
                    if (listBatch.Count > 0)
                    {
                        var count = 0;
                        foreach (var item in listBatch)
                        {
                            //清除中间库scsortdata
                            try
                            {
                                count = midsqlSugarClient.Deleteable<ScSortDatas>().Where(x => x.BatchName.Contains(item)).ExecuteCommand();
                                var endTime = DateTime.Now;
                                Log4NetHelper.Info($"清除sc_sort_data--{item}--成功，清除数量为:{count}");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"清除sc_sort_data,{ex}");
                            }
                            finally
                            {
                                Log4NetHelper.Debug($"清除sc_sort_data执行结束");
                            }
                        }

                        MessageBox.Show($"整体清除结束");


                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{ex.Message},{ex.StackTrace}");
                }
                finally
                {
                    btnClearDBData.BeginInvoke((MethodInvoker)delegate ()
                    {
                        btnClearDBData.Enabled = true;
                    });
                }
            });
        }

        private void btnClearMpr_Click(object sender, EventArgs e)
        {
           Task.Run(() =>
            {
                string filePath = lblMprPath.Text;
                var days = int.Parse(tbxMprDays.Text);
                var cutoff = DateTime.Now.AddDays(-days);
                int num = 0;

                object lockObj = new object();
                // 控制最大并行线程数，比如 8
                var options = new ParallelOptions
                {
                    MaxDegreeOfParallelism = 8
                };

                Parallel.ForEach(
                    Directory.EnumerateFiles(filePath, "*.mpr", SearchOption.TopDirectoryOnly),
                    options,
                    file =>
                    {
                        var info = new FileInfo(file);
                        if (info.LastWriteTime < cutoff)
                        {
                            try
                            {
                                File.Delete(file);
                                lock (lockObj) num++;
                            }
                            catch { }
                        }
                    }
                );
                //委托弹框提示
                btnClearMpr.BeginInvoke((MethodInvoker)delegate ()
                {
                    MessageBox.Show($"清除成功计数:{num}");
                });
                Log4NetHelper.Debug($"清除成功计数:{num}");

            });
            //异步清除日志
            /*Task.Run(() =>
            {
                try
                {
                    Log4NetHelper.Debug($"开始操作清除数据");
                    //根据日期清除日志文件夹下的日志文件 只清除包含.log的文件
                    string filePath = lblMprPath.Text;
                    //获取设置的天数
                    var days = int.Parse(tbxMprDays.Text);
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        DirectoryInfo dir = new DirectoryInfo(filePath);
                        int num = 0;
                        if (dir.Exists)
                        {
                            FileInfo[] files = dir.GetFiles();
                            Log4NetHelper.Debug($"获取总文件数成功:{files.Length}");
                            foreach (FileInfo file in files)
                            {
                                //如果日志在设置天数之前就删除
                                if (file.LastWriteTime < DateTime.Now.AddDays(-days) && file.FullName.Contains(".mpr"))
                                {
                                    file.Delete();
                                    num++;
                                }
                            }
                            Log4NetHelper.Debug($"清除成功计数:{num}");
                            MessageBox.Show($"清除成功计数:{num}");
                        }
                    }
                    else
                    {
                        //请选择正确的文件夹
                        MessageBox.Show("请选择正确的文件夹");
                    }
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Debug($"清除成功计数:{ex}");
                }

            });*/
        }

        private void btnSelMprPath_Click(object sender, EventArgs e)
        {
            //选择文件夹
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                lblMprPath.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void ClearData_Load(object sender, EventArgs e)
        {
            //string[] ports = SerialPort.GetPortNames();
            //MessageBox.Show(ports[0]);
        }

    }
}
